package plugin

import (
	"gitee.com/mkwchecking/k-scaffold/apps/register"
	"gitee.com/mkwchecking/k-scaffold/config"
	klog "gitee.com/mkwchecking/k-scaffold/pkg/rely/log/kratos"
	"github.com/go-kratos/kratos/v2/transport"
	"github.com/go-kratos/kratos/v2/transport/grpc"
)

func (p *Plugins) GetGrpc() (transport.Server, error) {
	if p._grpcSvr != nil {
		return p._grpcSvr, nil
	}

	grpcConf, err := config.GetGRPCServer()
	if err != nil {
		return nil, err
	}

	logger, err := p.GetLogger()
	if err != nil {
		return nil, err
	}

	ctx, err := p.HttpContext()
	if err != nil {
		return nil, err
	}

	srv := grpc.NewServer(
		grpc.Address(grpcConf.Addr),
		grpc.Network(grpcConf.Network),
		grpc.Timeout(grpcConf.Timeout),
		grpc.Logger(klog.NewLogger(logger.Logger)),
		grpc.Middleware(register.GetAppsMiddleware()...),
	)

	for _, app := range register.GetApps() {
		if grpcApp, ok := app.(register.IGrpcRegister); ok {
			if err := grpcApp.RegisterGrpcServer(ctx, srv); err != nil {
				return nil, err
			}
		}
	}

	p._grpcSvr = srv
	return p._grpcSvr, nil
}
